package com.ok.common.widget

import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.LinearGradient
import android.graphics.PixelFormat
import android.graphics.Shader
import android.graphics.drawable.Drawable
import android.widget.TextView
import com.ok.common.ext.Orientation

class ShaderDrawable(
    private val textView: TextView,
    private val colors: IntArray,
    private val orientation: Orientation
) : Drawable() {

    private var shader: Shader? = null

    override fun draw(canvas: Canvas) {
        val text = textView.text.toString()
        if (text.isEmpty()) return

        val width = textView.width
        val height = textView.height

        shader = when (orientation) {
            Orientation.HORIZONTAL -> LinearGradient(
                0f, 0f, width.toFloat(), 0f,
                colors, null, Shader.TileMode.CLAMP
            )

            Orientation.VERTICAL -> LinearGradient(
                0f, 0f, 0f, height.toFloat(),
                colors, null, Shader.TileMode.CLAMP
            )
        }

        textView.paint.shader = shader
        canvas.drawText(text, 0f, textView.lineHeight.toFloat(), textView.paint)
    }

    override fun setAlpha(alpha: Int) {}
    override fun setColorFilter(colorFilter: ColorFilter?) {}
    override fun getOpacity(): Int = PixelFormat.TRANSPARENT

}